package com.ymttest.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * Created by gejianhua on 2019/3/5.
 */
public class AESUtil {

    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);

    public static String encrypt(String toEncrypt, String key, String iv) {
        try {
            byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
            byte[] ivBytes = iv.getBytes(StandardCharsets.UTF_8);
            byte[] toEncryptBytes = toEncrypt.getBytes(StandardCharsets.UTF_8);

            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);
            return Base64.getEncoder().encodeToString(cipher.doFinal(toEncryptBytes));
        } catch (Exception e) {
            logger.error("AES decrypt exception, key:{}, iv:{}, toEncryptData:{}", key, iv, toEncrypt);
            throw new RuntimeException("AES encrypt exception", e);
        }
    }

    public static String decrypt(byte[] key, byte[] initVector, byte[] encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector);
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(encrypted);
            //byte[] original = cipher.doFinal(parseHexStr2Byte(encrypted));

            return new String(original);
        } catch (Exception e) {
            String keyStr = new String(key, StandardCharsets.UTF_8);
            String ivStr = new String(key, StandardCharsets.UTF_8);
            String encryptedStr = new String(encrypted, StandardCharsets.UTF_8);
            logger.error("AES decrypt exception, key:{}, iv:{}, encryptedData:{}", keyStr, ivStr, encryptedStr);
            throw new RuntimeException("AES decrypt exception", e);
        }
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        byte[] ivBytes = initVector.getBytes(StandardCharsets.UTF_8);
        byte[] encryptedBytes = encrypted.getBytes(StandardCharsets.UTF_8);
        return decrypt(keyBytes, ivBytes, encryptedBytes);
    }


}





































